const good = require('../../models/good/goods');
class GoodsService {
    static async getGoodsList({ pageNum = 1, pageSize = 10 }, data) {
        try {
            // 确保分页参数是数字类型
            const pageNumInt = parseInt(pageNum) || 1;
            const pageSizeInt = parseInt(pageSize) || 10;
            
            const query = {
                ...(data?.name && { name: { $regex: data.name, $options: 'i' } }),
                ...(data?.price && { price: { $gte: data.price } }),
                ...(data?.category && { category: data.category }),
                ...(data?.status && { status: data.status }),
                ...(data?.createTime && { createTime: { $gte: new Date(data.createTime) } }),
            };
            
            const skip = (pageNumInt - 1) * pageSizeInt;
            const limit = pageSizeInt;
            
            const total = await good.countDocuments(query);
            const goodsList = await good.find(query).skip(skip).limit(limit).populate('categoryId')
                .populate('tagId').lean();

            return {
                total,
                page: pageNumInt,
                totalPages: Math.ceil(total / pageSizeInt),
                list: goodsList
            };
        } catch (error) {
            throw new Error('获取商品列表失败: ' + error.message);
        }
    }
    static async getGoodsById(goodsId) {
        //连表查询categoryId相关信息及"tagId": ["683f1ac5bb38efc81cba6bd9"] 相关标签信息
        const goods = await good.findById(goodsId).populate('categoryId').populate('tagId').lean();
        return goods;
        // return await good.findById(goodsId).populate('categoryId').lean();
    }
    static async createGoods(goodsData) {
        return await good.create(goodsData);
    }
    static async getGoodsByIds(goodsIds) {
        return await good.find({ _id: { $in: goodsIds } }).populate("categoryId").lean();
    }
    static async updateGoods(goodsId, goodsData) {
        return await good.findByIdAndUpdate(goodsId, { $set: goodsData }, { new: true });
    }
    static async deleteGoods(goodsId, userId) {
        // 增加用户ID参数，确保用户只能删除自己创建的商品
        // 注意：这需要在商品模型中添加userId字段，并在创建商品时保存用户ID
        // return await good.findOneAndDelete({ _id: goodsId, userId: userId });
        
        // 当前实现暂时只按商品ID删除，后续应添加用户权限验证
        return await good.findByIdAndDelete(goodsId);
    }
}
module.exports = GoodsService;